import { useState, useEffect } from 'react';
import { useLanguage } from '@kernelproxy/i18n';
import { useAuth } from '../../contexts/AuthContext';
import { Users, Shield, Activity, Database, Search, Filter, UserPlus, Mail, Calendar, Tag, Edit, Trash2, Check, X } from 'lucide-react';

// 模拟用户数据类型
interface User {
  id: string;
  name: string;
  email: string;
  status: 'active' | 'inactive' | 'suspended';
  labels: string[];
  createdAt: string;
  lastLogin: string;
}

const AdminUserManagement = () => {
  const { language } = useLanguage();
  const { user } = useAuth();
  
  // 状态管理
  const [searchTerm, setSearchTerm] = useState('');
  const [filterRole, setFilterRole] = useState<string>('all');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
  const [showAddUser, setShowAddUser] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  
  // 模拟用户数据（实际应该从 Appwrite 数据库获取）
  const [users, setUsers] = useState<User[]>([
    {
      id: '1',
      name: 'Admin User',
      email: 'admin@kernelproxy.com',
      status: 'active',
      labels: ['admin'],
      createdAt: '2024-01-15',
      lastLogin: '2025-10-10'
    },
    {
      id: '2',
      name: 'John Doe',
      email: 'john@example.com',
      status: 'active',
      labels: ['vip'],
      createdAt: '2024-03-20',
      lastLogin: '2025-10-09'
    },
    {
      id: '3',
      name: 'Jane Smith',
      email: 'jane@example.com',
      status: 'active',
      labels: [],
      createdAt: '2024-05-10',
      lastLogin: '2025-10-08'
    },
    {
      id: '4',
      name: 'Bob Wilson',
      email: 'bob@example.com',
      status: 'suspended',
      labels: [],
      createdAt: '2024-02-28',
      lastLogin: '2025-09-15'
    },
    {
      id: '5',
      name: 'Alice Johnson',
      email: 'alice@example.com',
      status: 'active',
      labels: ['moderator', 'vip'],
      createdAt: '2024-04-05',
      lastLogin: '2025-10-10'
    },
  ]);

  const stats = [
    {
      title: language === 'zh-CN' ? '总用户数' : 'Total Users',
      value: users.length.toString(),
      icon: Users,
      color: 'bg-blue-500',
      change: '+12%'
    },
    {
      title: language === 'zh-CN' ? '活跃用户' : 'Active Users',
      value: users.filter(u => u.status === 'active').length.toString(),
      icon: Activity,
      color: 'bg-green-500',
      change: '+8%'
    },
    {
      title: language === 'zh-CN' ? '管理员' : 'Administrators',
      value: users.filter(u => u.labels.includes('admin')).length.toString(),
      icon: Shield,
      color: 'bg-purple-500',
      change: '0%'
    },
    {
      title: language === 'zh-CN' ? 'Premium 用户' : 'Premium Users',
      value: users.filter(u => u.labels.includes('vip')).length.toString(),
      icon: Database,
      color: 'bg-orange-500',
      change: '+25%'
    },
  ];

  // 过滤用户
  const filteredUsers = users.filter(user => {
    const matchesSearch = user.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         user.email.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesRole = filterRole === 'all' || user.labels.includes(filterRole);
    const matchesStatus = filterStatus === 'all' || user.status === filterStatus;
    
    return matchesSearch && matchesRole && matchesStatus;
  });

  // 角色标签样式
  const getRoleBadgeStyle = (label: string) => {
    switch (label) {
      case 'admin':
        return 'bg-gradient-to-r from-purple-600 to-pink-600 text-white';
      case 'moderator':
        return 'bg-blue-500 text-white';
      case 'vip':
        return 'bg-yellow-500 text-white';
      case 'subscriber':
        return 'bg-green-500 text-white';
      default:
        return 'bg-gray-500 text-white';
    }
  };

  // 状态标签样式
  const getStatusBadgeStyle = (status: string) => {
    switch (status) {
      case 'active':
        return 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400';
      case 'inactive':
        return 'bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-400';
      case 'suspended':
        return 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  // 选择/取消选择用户
  const toggleUserSelection = (userId: string) => {
    setSelectedUsers(prev =>
      prev.includes(userId)
        ? prev.filter(id => id !== userId)
        : [...prev, userId]
    );
  };

  // 全选/取消全选
  const toggleSelectAll = () => {
    if (selectedUsers.length === filteredUsers.length) {
      setSelectedUsers([]);
    } else {
      setSelectedUsers(filteredUsers.map(u => u.id));
    }
  };

  // 删除用户
  const handleDeleteUser = (userId: string) => {
    if (confirm(language === 'zh-CN' ? '确定要删除这个用户吗？' : 'Are you sure you want to delete this user?')) {
      setUsers(prev => prev.filter(u => u.id !== userId));
      setSelectedUsers(prev => prev.filter(id => id !== userId));
    }
  };

  // 批量删除
  const handleBulkDelete = () => {
    if (confirm(language === 'zh-CN' 
      ? `确定要删除选中的 ${selectedUsers.length} 个用户吗？` 
      : `Are you sure you want to delete ${selectedUsers.length} selected users?`)) {
      setUsers(prev => prev.filter(u => !selectedUsers.includes(u.id)));
      setSelectedUsers([]);
    }
  };

  // 更新用户角色
  const handleUpdateUserLabels = (userId: string, newLabels: string[]) => {
    setUsers(prev => prev.map(u => 
      u.id === userId ? { ...u, labels: newLabels } : u
    ));
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="bg-gradient-to-r from-purple-600 to-pink-600 rounded-lg p-6 text-white">
        <div className="flex items-center justify-between">
          <div>
            <div className="flex items-center space-x-3 mb-2">
              <Shield size={32} />
              <h1 className="text-3xl font-bold">
                {language === 'zh-CN' ? '用户管理' : 'User Management'}
              </h1>
            </div>
            <p className="text-purple-100">
              {language === 'zh-CN' 
                ? '管理系统用户、权限和访问控制' 
                : 'Manage system users, permissions and access control'}
            </p>
            <div className="mt-4 flex items-center space-x-2 bg-white/20 rounded-lg px-4 py-2 w-fit">
              <span className="text-sm">
                {language === 'zh-CN' ? '当前登录为' : 'Logged in as'}:
              </span>
              <span className="font-semibold">{user?.name || user?.email}</span>
              <span className="px-2 py-0.5 text-xs font-semibold bg-white text-purple-600 rounded-full">
                {language === 'zh-CN' ? '管理员' : 'Admin'}
              </span>
            </div>
          </div>
          <button
            onClick={() => setShowAddUser(true)}
            className="bg-white text-purple-600 px-4 py-2 rounded-lg hover:bg-purple-50 transition-colors flex items-center space-x-2"
          >
            <UserPlus size={20} />
            <span>{language === 'zh-CN' ? '添加用户' : 'Add User'}</span>
          </button>
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {stats.map((stat, index) => (
          <div
            key={index}
            className="bg-white dark:bg-gray-800 rounded-lg p-6 shadow-md hover:shadow-lg transition-shadow"
          >
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-1">
                  {stat.title}
                </p>
                <p className="text-2xl font-bold text-gray-900 dark:text-white">
                  {stat.value}
                </p>
                <p className="text-xs text-green-600 dark:text-green-400 mt-1">
                  {stat.change} {language === 'zh-CN' ? '本月' : 'this month'}
                </p>
              </div>
              <div className={`${stat.color} p-3 rounded-lg`}>
                <stat.icon size={24} className="text-white" />
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Filters and Search */}
      <div className="bg-white dark:bg-gray-800 rounded-lg p-6 shadow-md">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          {/* Search */}
          <div className="md:col-span-2">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
              <input
                type="text"
                placeholder={language === 'zh-CN' ? '搜索用户名或邮箱...' : 'Search by name or email...'}
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              />
            </div>
          </div>

          {/* Role Filter */}
          <div>
            <select
              value={filterRole}
              onChange={(e) => setFilterRole(e.target.value)}
              className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-500 focus:border-transparent"
            >
              <option value="all">{language === 'zh-CN' ? '所有角色' : 'All Roles'}</option>
              <option value="admin">{language === 'zh-CN' ? '管理员' : 'Admin'}</option>
              <option value="moderator">{language === 'zh-CN' ? '版主' : 'Moderator'}</option>
              <option value="vip">VIP</option>
            </select>
          </div>

          {/* Status Filter */}
          <div>
            <select
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value)}
              className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-500 focus:border-transparent"
            >
              <option value="all">{language === 'zh-CN' ? '所有状态' : 'All Status'}</option>
              <option value="active">{language === 'zh-CN' ? '活跃' : 'Active'}</option>
              <option value="inactive">{language === 'zh-CN' ? '未激活' : 'Inactive'}</option>
              <option value="suspended">{language === 'zh-CN' ? '已停用' : 'Suspended'}</option>
            </select>
          </div>
        </div>

        {/* Bulk Actions */}
        {selectedUsers.length > 0 && (
          <div className="mt-4 flex items-center justify-between bg-purple-50 dark:bg-purple-900/20 rounded-lg p-4">
            <span className="text-sm text-purple-900 dark:text-purple-300">
              {language === 'zh-CN' 
                ? `已选择 ${selectedUsers.length} 个用户` 
                : `${selectedUsers.length} users selected`}
            </span>
            <div className="flex space-x-2">
              <button
                onClick={handleBulkDelete}
                className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors flex items-center space-x-2"
              >
                <Trash2 size={16} />
                <span>{language === 'zh-CN' ? '批量删除' : 'Delete Selected'}</span>
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Users Table */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-md overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 dark:bg-gray-700 border-b border-gray-200 dark:border-gray-600">
              <tr>
                <th className="px-6 py-3 text-left">
                  <input
                    type="checkbox"
                    checked={selectedUsers.length === filteredUsers.length && filteredUsers.length > 0}
                    onChange={toggleSelectAll}
                    className="rounded border-gray-300 text-purple-600 focus:ring-purple-500"
                  />
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {language === 'zh-CN' ? '用户' : 'User'}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {language === 'zh-CN' ? '状态' : 'Status'}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {language === 'zh-CN' ? '角色' : 'Roles'}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {language === 'zh-CN' ? '注册日期' : 'Joined'}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {language === 'zh-CN' ? '最后登录' : 'Last Login'}
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {language === 'zh-CN' ? '操作' : 'Actions'}
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
              {filteredUsers.map((user) => (
                <tr key={user.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors">
                  <td className="px-6 py-4">
                    <input
                      type="checkbox"
                      checked={selectedUsers.includes(user.id)}
                      onChange={() => toggleUserSelection(user.id)}
                      className="rounded border-gray-300 text-purple-600 focus:ring-purple-500"
                    />
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center">
                      <div className="w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center text-white font-semibold">
                        {user.name.charAt(0).toUpperCase()}
                      </div>
                      <div className="ml-4">
                        <div className="text-sm font-medium text-gray-900 dark:text-white">
                          {user.name}
                        </div>
                        <div className="text-sm text-gray-500 dark:text-gray-400 flex items-center">
                          <Mail size={14} className="mr-1" />
                          {user.email}
                        </div>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <span className={`px-2 py-1 text-xs font-semibold rounded-full ${getStatusBadgeStyle(user.status)}`}>
                      {user.status.charAt(0).toUpperCase() + user.status.slice(1)}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex flex-wrap gap-1">
                      {user.labels.length > 0 ? (
                        user.labels.map((label, idx) => (
                          <span
                            key={idx}
                            className={`px-2 py-0.5 text-xs font-semibold rounded-full ${getRoleBadgeStyle(label)}`}
                          >
                            {label}
                          </span>
                        ))
                      ) : (
                        <span className="text-xs text-gray-400">
                          {language === 'zh-CN' ? '无角色' : 'No roles'}
                        </span>
                      )}
                    </div>
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-500 dark:text-gray-400">
                    <div className="flex items-center">
                      <Calendar size={14} className="mr-1" />
                      {user.createdAt}
                    </div>
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-500 dark:text-gray-400">
                    {user.lastLogin}
                  </td>
                  <td className="px-6 py-4 text-right">
                    <div className="flex justify-end space-x-2">
                      <button
                        onClick={() => setEditingUser(user)}
                        className="p-2 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg transition-colors"
                        title={language === 'zh-CN' ? '编辑' : 'Edit'}
                      >
                        <Edit size={16} />
                      </button>
                      <button
                        onClick={() => handleDeleteUser(user.id)}
                        className="p-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
                        title={language === 'zh-CN' ? '删除' : 'Delete'}
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {filteredUsers.length === 0 && (
          <div className="text-center py-12">
            <Users size={48} className="mx-auto text-gray-400 mb-4" />
            <p className="text-gray-500 dark:text-gray-400">
              {language === 'zh-CN' ? '没有找到匹配的用户' : 'No users found'}
            </p>
          </div>
        )}
      </div>

      {/* Implementation Guide */}
      <div className="bg-blue-50 dark:bg-blue-900/20 border-l-4 border-blue-600 rounded-lg p-6">
        <h3 className="text-lg font-bold text-blue-900 dark:text-blue-300 mb-3">
          {language === 'zh-CN' ? '📌 实现说明' : '📌 Implementation Notes'}
        </h3>
        <div className="space-y-2 text-blue-800 dark:text-blue-200 text-sm">
          <p>
            <strong>{language === 'zh-CN' ? '当前状态：' : 'Current Status:'}</strong> 
            {language === 'zh-CN' 
              ? '此页面使用模拟数据进行演示。' 
              : 'This page uses mock data for demonstration.'}
          </p>
          <p>
            <strong>{language === 'zh-CN' ? '生产环境：' : 'For Production:'}</strong>
          </p>
          <ul className="list-disc list-inside ml-4 space-y-1">
            <li>
              {language === 'zh-CN' 
                ? '需要使用 Appwrite Users API (服务端 SDK) 获取用户列表' 
                : 'Use Appwrite Users API (Server SDK) to fetch user list'}
            </li>
            <li>
              {language === 'zh-CN' 
                ? '通过 Appwrite Functions 实现用户管理操作' 
                : 'Implement user management via Appwrite Functions'}
            </li>
            <li>
              {language === 'zh-CN' 
                ? '使用 users.updateLabels() 更新用户角色标签' 
                : 'Use users.updateLabels() to update user role labels'}
            </li>
            <li>
              {language === 'zh-CN' 
                ? '所有操作需要服务端 API Key 权限验证' 
                : 'All operations require server-side API key authentication'}
            </li>
          </ul>
        </div>
      </div>
    </div>
  );
};

export default AdminUserManagement;
